
/*
 * @Description: node中的发布订阅
 * @Version: 1.0
 * @Autor: ziwei
 * @Date: 2021-04-25 15:38:22
 * @LastEditors: ziwei
 * @LastEditTime: 2021-04-25 15:39:46
 */
function EventEmitter(params) {
    this._events = {}
}

//订阅
EventEmitter.prototype.on = function (eventName, callback) {
    if (!this._events) {
        this._events = {}
    }
    if (this._events[eventName]) {
        this._events[eventName].push(callback);
    } else {
        this._events[eventName] = [callback];
    }
}

//发布
EventEmitter.prototype.emit = function (eventName, ...arg) {
    this._events[eventName].forEach(fn => {
        fn(...arg);
    });
}

//解绑事件
EventEmitter.prototype.off = function (eventName, callback) {
    if (this._events && this._events[eventName]) {
        this._events[eventName].filter(fn => {
            return (fn[eventName] !== callback && fn.l == callback)
        });
    }
}

// 只触发一次
EventEmitter.prototype.once = (eventName, callback) => {
    let one = this.on(eventName, () => {//绑定执行完毕后移除
        callback();
        one.l = callback;
        this.off(eventName, one)
    })
    this.on(eventName, on);
}

module.exports = EventEmitter;
